package service

import (
	"product-service/common"
	"product-service/dao"
	"product-service/dao/entity"
	"product-service/utils/result"
)

var (
	PmsCategoryService = &pmsCategoryService{}
)

type pmsCategoryService struct {
}

func (t *pmsCategoryService) FindCatIdArray(id int64) *common.CommonReponse {
	//dao.PmsCategoryDao.FindCategoryArray2()
	array, err := dao.PmsCategoryDao.FindCategoryArray(dao.DB, id)
	if err != nil {
		return common.Error.WithMsg(err.Error())
	}
	return common.OK.WithData(array)
}

func (t *pmsCategoryService) DeleteById(id int64) *common.CommonReponse {
	_, err := dao.PmsCategoryDao.FindById(dao.DB, id)
	if err != nil {
		return common.Error.WithMsg(err.Error())
	}
	err = dao.PmsCategoryDao.DeleteById(dao.DB, id)
	if err != nil {
		return common.Error.WithMsg(err.Error())
	}
	return common.OK.WithData(nil)
}

func (t *pmsCategoryService) UpdateById(id int64, model *entity.PmsCategory) *common.CommonReponse {
	//先查询后修改
	_, err := dao.PmsCategoryDao.FindById(dao.DB, id)
	if err != nil {
		return common.Error.WithMsg(err.Error())
	}
	//开启事务
	begin := dao.DB.Begin()
	err = dao.PmsCategoryDao.UpdateById(begin, id, model)
	if err != nil {
		return common.Error.WithMsg(err.Error())
	}
	//更新中间表
	err = dao.PmsCategoryBrandRelationDao.UpdateCategory(begin, id, model.Name)
	if err != nil {
		return common.Error.WithMsg(err.Error())
	}
	begin.Commit()
	return common.OK
}

func (t *pmsCategoryService) Save(model *entity.PmsCategory) *common.CommonReponse {
	data, err := dao.PmsCategoryDao.Save(dao.DB, model)
	if err != nil {
		return common.Error.WithMsg(err.Error())
	}
	return common.OK.WithData(data)
}

func (t *pmsCategoryService) FindById(id int64) *common.CommonReponse {
	data, err := dao.PmsCategoryDao.FindById(dao.DB, id)
	if err != nil {
		return common.Error.WithMsg(err.Error())
	}
	return common.OK.WithData(data)
}

func (t *pmsCategoryService) FindAll(pageQuery *common.PageQuery) *common.CommonReponse {
	all, i, err := dao.PmsCategoryDao.FindAll(dao.DB, pageQuery)
	page := &common.Page{
		Total: i,
		Data:  all,
	}
	if err != nil {
		return common.Error.WithMsg(err.Error())
	}
	return common.OK.WithData(page)
}

func (t *pmsCategoryService) FindTree() *common.CommonReponse {
	tree, err := dao.PmsCategoryDao.FindTree(dao.DB)
	if err != nil {
		return common.Error.WithMsg(err.Error())
	}
	return common.OK.WithData(tree)
}

func (t *pmsCategoryService) UpdateBatch(models []*entity.PmsCategory) *common.CommonReponse {
	err := dao.PmsCategoryDao.UpdateBatch(dao.DB, models)
	if err != nil {
		return result.CategoryUpdateBatchError
	}
	return common.OK
}

func (t *pmsCategoryService) DeleteBatch(ids []int64) *common.CommonReponse {
	err := dao.PmsCategoryDao.DeleteBatch(dao.DB, ids)
	if err != nil {
		return result.CategoryDeleteBatchError
	}
	return common.OK
}
